﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class LevelCircleButton : MonoBehaviour
{
    public List<Button> buttonList = new List<Button>();
    private List<int> indexList = new List<int>();
    private float colorChangeRate = 1;
    public Text loveText;
    public GameLevelItem gameLevelItem;
    // Start is called before the first frame update
    void Start()
    {
        InitIndexList();
        InitButtonEvent();
        NextBlackButton();
        loveText.color = new Color(0, 0, 0, 0);
    }

    private void InitIndexList()
    {
        int count = buttonList.Count;
        for (int i = 0; i < count; i++)
        {
            indexList.Add(i);
        }
    }

    private void InitButtonEvent()
    {
        int count = buttonList.Count;
        for (int i = 0; i < count; i++)
        {
            int index = i;
            buttonList[i].image.color = Color.white;
            buttonList[i].onClick.AddListener(() =>
            {
                if (buttonList[index].image.color == Color.red)
                {
                    buttonList[index].enabled = false;
                    indexList.Remove(index);
                }
                SoundManager.Instance.PlayAudio(SoundType.Click.ToString(), false);
                UpdateLoveTextColor();
            });

        }
    }

    private void UpdateLoveTextColor()
    {
        float alpha = 0;
        float indexCount = indexList.Count;
        float buttonCount = buttonList.Count;
        alpha = 1 - (indexCount / buttonCount);
        loveText.color = new Color(0, 0, 0, alpha);
        if (indexCount < 1)
        {
            gameLevelItem.TriggerResult(true);
        }
    }

    private void NextBlackButton()
    {
        int indexListCount = indexList.Count;
        if (indexListCount > 0)
        {
            int index = Random.Range(0, indexListCount);
            for (int i = 0; i < indexListCount; i++)
            {
                buttonList[indexList[i]].image.color = i == index ? Color.red : Color.white;
            }

            Invoke("NextBlackButton", colorChangeRate);
        }
    }
}
